//
//  OAuthViewController.swift
//  Swiftsweibo
//
//  Created by 张鹏飞 on 16/1/6.
//  Copyright © 2016年 张鹏飞. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    //MARK: - 监听方法
    @objc private func close() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充用户名和密码
    @objc private func autoFill() {
    
        let js = "document.getElementById('userId').value = 'mantouaicai@sina.com';" +
        "document.getElementById('passwd').value = 'zpf945157';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //MARK: - 界面设置
    override func loadView() {
        
        view = webView
        title = "登录微博界面"
        
        //设置代理
        webView.delegate = self
        
        //关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        //自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载页面
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthURL))
    }
}

//MARK: - UIWebViewDelegate
extension OAuthViewController: UIWebViewDelegate {

    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView
    /// - parameter request:        request
    /// - parameter navigationType: navigationType 页面跳转的方式
    ///
    /// - returns: 返回 false 不加载, 返回 true 继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        //目标如果是百度就不加载
        //1.判断访问的主机是否是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
        
            return true
        }
        //2.从百度地址的 URL 中提取"code="是否存在
        guard let query = url.query where query.hasPrefix("code=")else {
        
            print("授权取消")
            close()
            
            return false
        }
        //3.从query字符串中提取"code="后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        
//        print(query)
        
       // 4.加载 AcrossToken
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if !isSuccessed {
            
                print("失败了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                    
//                    self.close()
//                })
                delay(0.5) { self.close() }
                return
            }
            
                print("成功了")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                SVProgressHUD.dismiss()
                
/// 发送通知切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            })
        }
     
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}







